<template>
  <!-- 菌落形态明细 -->
  <div id="colonialMorphologyDetail" v-loading="loading">
    <el-scrollbar style="height: 100%">
      <el-descriptions size="default" class="CMTypeBox" labelClassName="CMTypeBox-title" border v-for="(item, index) in colonialMorphologyTypeList" :key="index">
        <el-descriptions-item label-class-name="my-label">
          <template #label>
            <span>{{ item.name }}</span>
            <div>
              <vxe-button type="text" class-name="vxe-icon-delete-fill text-red" content="清除选中" @click="clearOptionChecked(item.code)"></vxe-button>
            </div>
          </template>
          <el-row :gutter="10">
            <el-col :span="3" v-for="(op, idx) in item.colonialMorphologyTypeOptList" :key="idx" class="text item">
              <el-card shadow="never">
                <el-upload ref="uploadRef" :data="{id:op.id}" :headers="headers" :action="uploaduri" :show-file-list="false" :on-success="getColonialMorphologyTypeList" class="upload-demo" :auto-upload="true">
                  <template #trigger>
                    <el-image style="width: 100%; height: 50px;text-align: center;vertical-align: middle;" :src="byteArrayToImage(op.imageBlob)" fit="contain">
                      <!-- picUrlBase + op.imageUrl -->
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </template>
                </el-upload>
              </el-card>
              <div>
                <el-radio v-model="radioArr[item.code]" :label="op.id" @change="radioChange(item.code)">
                  {{ op ? op.name : '' }}
                </el-radio>
              </div>
            </el-col>
          </el-row>
        </el-descriptions-item>
      </el-descriptions>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { VxeMessage, VxeNotifyType } from "@/utils/CommonMessage";
import { Picture as IconPicture } from '@element-plus/icons-vue'

let { proxy }: any = getCurrentInstance();
let loading = ref(false); //查询按钮加载
let form = reactive({
  colonialMorphologyId: null, //菌落形态Id
  colonialMorphologyTypeId: null, //菌落形态类型ID
  colonialMorphologyTypeOptionId: null //菌落形态类型可选项Id
});
let radioArr = reactive({});//选中的菌落形态类型可选项id(ps: 菌落形态类型作为键名)
let colonialMorphologyTypeList = reactive([]);//菌落形态类型
let colonialMorphologyTypeOptList = reactive([]);//菌落形态类型可选项
let picUrlBase = (window as any).apiUrl.VITE_SERVER_URL;
const uploaduri = `${(window as any).apiUrl.VITE_SERVER_URL}/bac/germ/morphologyType/uploadMorphologyTypeImage`;
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};
// 方法定义区 =============

defineExpose({
  colonialMorphologyIdChange
})

// 页面加载时
onMounted(() => {
  getColonialMorphologyTypeList();
});

function clearOptionChecked(code) {
  colonialMorphologyTypeList.forEach((e) => {
    if (e.code === code) {
      radioArr[code] = null;
      save(code);
    }
  });
}

function colonialMorphologyIdChange(id) {
  form.colonialMorphologyId = id;
  if (id) {
    findColonialMorphologyDetailLsit(id, false);
  } else {
    Object.assign({}, radioArr);
  }
}

// 获取菌落形态明细 isToParent: 是否往父组件传值，当有数据保存时才为true
function findColonialMorphologyDetailLsit(id, isToParent) {
  loading.value = true;
  const url = '/bac/germ/morphology/findListByMorphologyId';
  const data = {
    id: id
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      // 设置变量接收所有菌落形态明细name
      const nameArr = [];
      Object.keys(radioArr).forEach(key => {
        radioArr[key] = null;
      });
      res.data.forEach((item, index) => {
        radioArr[item.morphologyType] = item.id;
        if (item.name) {
          nameArr.push(item.name);
        }
      });
      const nameStr = nameArr.join('、');
      // 当参数 isToParent 为true时，才往父组件传值
      if (isToParent) {
        proxy.$emit('setDetailName', { id: id, name: nameStr });
      }
      loading.value = false;
    })
    .catch(err => {
      loading.value = false;
      proxy.$alert(err.data.error.message, '提示');
    });
}

// 获取菌落形态类型
function getColonialMorphologyTypeList() {

  colonialMorphologyTypeList.length = 0;
  loading.value = true;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'gremMorphologyType' } })
    .then((res: any) => {
      /*radioArr = {};*/
      Object.assign(colonialMorphologyTypeList, res.data);
      res.data.forEach((item, index) => {
        // radioArr[item.code]=null;
        getColonialMorphologyTypeOptList(item, index);
      });
      loading.value = false;
    })
    .catch(err => {
    });
}

// 获取菌落形态类型可选项
function getColonialMorphologyTypeOptList(value, index) {
  const url = '/bac/germ/morphologyType/findListByType';
  const data = {
    morphologyType: value.code
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      value.radio = null;
      value.colonialMorphologyTypeOptList = res.data;
      colonialMorphologyTypeList[index] = Object.assign({}, value);
      proxy.$forceUpdate();
    })
    .catch(err => {
      proxy.$alert(err.data.error.message, '提示');
    });
}

// 单选框选中改变
function radioChange(id) {
  save(id);
}

// 保存
function save(keyId) {
  loading.value = true;
  const url = '/bac/germ/morphology/saveMorphologys';
  const data = {
    morphologyId: form.colonialMorphologyId,
    morphologyType: keyId,
    morphologyTypeId: radioArr[keyId]
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      findColonialMorphologyDetailLsit(form.colonialMorphologyId, true);
      loading.value = false;
    })
    .catch(err => {
      loading.value = false;
      VxeMessage('保存失败', VxeNotifyType.error);
    });
}
/* byte[] 转涂片 */
function byteArrayToImage(byteArray) {
  return `data:image/jpeg;base64,${byteArray}`;
}
</script>
<style lang="scss" scoped>
#colonialMorphologyDetail {
  height: 100%;

  .CMTypeBox {
    margin-bottom: 5px;

    .CMTypeBox-title {
      color: #333;
      font-size: 14px;
      width: 70px;
    }
    :deep(.my-label) {
      font-size: 15px;
      width: 100px;
    }

    .el-col > div:last-child {
      text-align: center;

      .el-radio {
        margin-top: 4px;

        .el-radio__label {
          font-size: 12px;
        }
      }
    }
  }

  :deep(.el-card__body) {
    padding: 0;
    margin: 0;

    .image-slot {
      height: 100%;
      width: 100%;
      text-align: center;
      display: table;

      i {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
      }
    }
  }
}

:deep(.el-upload) {
  width: 100%;
}
</style>
